//
//  BIDActivityDetailViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/26.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDActivityDetailViewController.h"
#import "BIDActivityDetailHeaderView.h"
#import "BIDActivityDetailCell.h"
#import <SDWebImage/UIImageView+WebCache.h>

//获取活动详情
static NSString *activityDetailURL = @"activityAndroid/getActivityById.action";
//报名
static NSString *applyURL = @"activityMemberAndroid/add.action";

@interface BIDActivityDetailViewController ()<UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate>
{
    NSDictionary *_activityDic;
    NSArray *_dataSourceArr;
    BIDActivityDetailHeaderView *_headerView;
    UIView *_footerView;
    BIDActivityDetailCell *_tempDetailCell;
    BOOL _bRegister;
}
@end

@implementation BIDActivityDetailViewController
@synthesize activityID;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"详情";
    _activityDic = [[NSDictionary alloc] init];
    _dataSourceArr = [[NSArray alloc] init];
    //
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDActivityDetailHeaderView" owner:self options:nil] lastObject];
    //
    _tempDetailCell = [[[NSBundle mainBundle] loadNibNamed:@"BIDActivityDetailCell" owner:self options:nil] lastObject];
    //
    [BIDGlobalMethods setImgForBtn:_btn imgName:@"cyanBtnBg_normal.png" state:UIControlStateNormal inset:UIEdgeInsetsMake(10, 10, 11, 11)];
    [BIDGlobalMethods setImgForBtn:_btn imgName:@"cyanBtnBg_highlight.png" state:UIControlStateHighlighted inset:UIEdgeInsetsMake(10, 10, 11, 11)];
    [BIDGlobalMethods setImgForBtn:_btn imgName:@"btnBg_disenable.png" state:UIControlStateDisabled inset:UIEdgeInsetsMake(10, 10, 11, 11)];
    //
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], activityDetailURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"activity.id=%@&searchParam.memberId=%@", activityID, [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            _activityDic = [[NSDictionary alloc] initWithDictionary:responseDic];

            //是否已报名
            BOOL isSign = [_activityDic[@"isSign"] intValue]==0 ? NO : YES;
            if(isSign)
            {
                [_btn setEnabled:NO];
                [_btn setTitle:@"已报名" forState:UIControlStateNormal];
            }
            else
            {
                //根据states字段判断活动的状态
                NSNumber *stateValue = responseDic[@"states"];
                switch([stateValue intValue])
                {
                    case 1:
                    {
                        //可报名
                        [_btn setEnabled:YES];
                        [_btn setTitle:@"报 名" forState:UIControlStateNormal];
                    }
                        break;
                    case 2:
                    {
                        [_btn setEnabled:NO];
                        [_btn setTitle:@"报名已结束" forState:UIControlStateNormal];
                    }
                        break;
                    case 3:
                    {
                        [_btn setEnabled:NO];
                        [_btn setTitle:@"活动进行中" forState:UIControlStateNormal];
                    }
                        break;
                    case 4:
                    {
                        [_btn setEnabled:NO];
                        [_btn setTitle:@"活动已结束" forState:UIControlStateNormal];
                    }
                        break;
                }
            }
            //报名截止时间
            NSString *strApplyStopTime = responseDic[@"stopTime"];
            NSString *strActivityTime = [[NSString alloc] initWithFormat:@"%@~%@", responseDic[@"startTime"], responseDic[@"endTime"]];
            NSString *strPlace = responseDic[@"place"];
            NSString *strApplyCondition = [[NSString alloc] initWithFormat:@"已报名%@人（限制名额%@人)", responseDic[@"signNum"], responseDic[@"restricts"]];
            _dataSourceArr = @[@{@"title":@"报名截止时间", @"value":strApplyStopTime},
                               @{@"title":@"活动时间", @"value":strActivityTime},
                               @{@"title":@"活动地点", @"value":strPlace},
                               @{@"title":@"", @"value":strApplyCondition}];
            //
            _tableView.tableHeaderView = [self createHeaderView];
            //
            _tableView.tableFooterView = [self createFooterView];
            //
            [_tableView reloadData];
        }
    }];
}

/**
 创建tableHeaderView

 @return <#return value description#>
 */
- (UIView *)createHeaderView
{
    NSNumber *isNeedPayValue = _activityDic[@"isPay"];
    NSString *strTitle = _activityDic[@"title"];
    NSString *strPrice = @"";
    if([isNeedPayValue intValue] == 0)
    {
        strPrice = @"(免费)";
    }
    else
    {
        strPrice = [[NSString alloc] initWithFormat:@"(￥%@)", _activityDic[@"price"]];
    }
    NSString *strIntegratedTitle = [[NSString alloc] initWithFormat:@"%@  %@", strTitle, strPrice];
    NSMutableAttributedString *strAttribute = [[NSMutableAttributedString alloc] initWithString:strIntegratedTitle];
    if([isNeedPayValue intValue] == 0)
    {
        [strAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(strTitle.length+2, strPrice.length)];
    }
    else
    {
        [strAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(strTitle.length+2, strPrice.length)];
    }
    NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], _activityDic[@"titleImage"]];
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat height = [BIDGlobalMethods getHeightWithAttributeString:strAttribute constraintSize:CGSizeMake(screenSize.width-19, MAXFLOAT)];
    if(height > 25)
    {
        _headerView.heightForTitleLabelConstraint.constant = height;
    }
    CGRect frame = _headerView.frame;
    frame.size.height = 225*screenSize.width / 320;
    frame.size.height += (height-25);
    _headerView.frame = frame;
    [_headerView layoutIfNeeded];
    [_headerView.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"slide_placeholder.png"]];
    _headerView.titleLabel.attributedText = strAttribute;
    return _headerView;
}

/**
 创建tableFooterView

 @return <#return value description#>
 */
- (UIView *)createFooterView
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, 0)];
    [_footerView setBackgroundColor:[UIColor whiteColor]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_footerView.frame), 35.f)];
    [label setText:@"   活动介绍"];
    [label setTextColor:[UIColor blackColor]];
    [label setBackgroundColor:RGBACOLOR(241.f, 241.f, 241.f, 1.f)];
    [_footerView addSubview:label];
    //
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[_activityDic[@"content"] dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    CGFloat contentHeight = [BIDGlobalMethods getHeightWithAttributeString:attrStr constraintSize:CGSizeMake(CGRectGetWidth(_footerView.frame)-32, MAXFLOAT)];
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, CGRectGetHeight(label.frame)+5, CGRectGetWidth(_footerView.frame)-32, contentHeight)];
    contentLabel.numberOfLines = 0;
    //
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(16, CGRectGetHeight(label.frame)+5, CGRectGetWidth(_footerView.frame)-32, contentHeight)];
    webView.delegate = self;
    [webView loadHTMLString:attrStr.string baseURL:nil];
    CGRect webViewFrame = webView.frame;
    CGFloat webViewHeight = webView.scrollView.contentSize.height;
    webViewFrame.size.height = webViewHeight;
    webView.frame = webViewFrame;
    [_footerView addSubview:webView];
    //
    CGRect footerViewFrame = _footerView.frame;
    footerViewFrame.size.height = webViewHeight + CGRectGetHeight(label.frame) + 10;
    _footerView.frame = footerViewFrame;
    return _footerView;
}

/**
 报名

 @param sender <#sender description#>
 */
- (IBAction)btnDownHandler:(id)sender
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], applyURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"activityMember.activityId=%@&memberId=%@", _activityDic[@"id"], [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [self showHint:@"报名成功"];
            [_btn setEnabled:NO];
            [_btn setTitle:@"已报名" forState:UIControlStateNormal];
        }
    }];
}


#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    webViewHeight = webView.scrollView.contentSize.height;
    //
    CGRect webViewFrame = webView.frame;
    webViewFrame.size.height = webViewHeight;
    webView.frame = webViewFrame;
    //
    CGRect footerViewFrame = _footerView.frame;
    footerViewFrame.size.height = webViewHeight + 35 + 10;
    _footerView.frame = footerViewFrame;
    _tableView.tableFooterView = _footerView;
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    static NSString *identifier1 = @"identifier1";
    NSUInteger row = indexPath.row;
    NSDictionary *dic = _dataSourceArr[row];
    NSString *strTitle = dic[@"title"];
    if(strTitle.length == 0)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier1];
        }
        cell.textLabel.text = dic[@"value"];
    }
    else
    {
        if(!_bRegister)
        {
            _bRegister = YES;
            UINib *nib = [UINib nibWithNibName:@"BIDActivityDetailCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:identifier];
        }
        BIDActivityDetailCell *detailCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        detailCell.titleLabel.text = dic[@"title"];
        detailCell.contentLabel.text = dic[@"value"];
        cell = detailCell;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = indexPath.row;
    NSDictionary *dic = _dataSourceArr[row];
    NSString *strTitle = dic[@"title"];
    if(strTitle.length == 0)
    {
        return 44.f;
    }
    else
    {
        return 71.f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
